package com.rabbitmq.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.common.Constant.NUM5;
import static com.rabbitmq.common.Constant.NUM6000;

/**
 * @className: CommonConfirm
 * @description: 普通确认
 * @date: 2020/5/14
 * @author: cakin
 */
@Slf4j
public class BatchConfirm {
    public static void main( String[] args ) {
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare("exchange.confirm", "direct", true, false, null);
            channel.queueDeclare("queue.confirm", true, false, false, null);
            channel.queueBind("queue.confirm", "exchange.confirm", "routingKey");
            // 启动confirm模式
            channel.confirmSelect();
            // 批量发送消息
            for (int i = 0; i < NUM5; i++) {
                String msg = String.format("时间 => %s", new Date().getTime());
                channel.basicPublish("exchange.confirm", "routingKey", MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
            }
            try {
                // 直到所有信息都发布，只要有一个未确认就会IOException
                channel.waitForConfirmsOrDie();
                // 客户端收到了Basic.Ack
                log.info("全部发送成功");
            } catch (IOException e) { // 客户端收到了Basic.Nack
                log.info("catch IOException");
                log.info("发送失败");
                log.info("重发消息逻辑");
            } catch (InterruptedException e) {
                // 被中断,抛出InterruptedException
                log.info("catch InterruptedException");
            }
            ConnectionUtils.close(channel, connection);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }


}
